import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/settings_provider.dart';
import '../l10n/app_localizations.dart';
import '../services/log_service.dart';
import 'server_diagnostic_screen.dart';

class SettingsScreen extends StatelessWidget {
  const SettingsScreen({super.key});

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context);
    
    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.navSettings),
      ),
      body: Consumer<SettingsProvider>(
        builder: (context, settings, _) {
          return ListView(
            children: [
              _SettingsSection(
                title: l10n.translate('settings_connection'),
                children: [
                  SwitchListTile(
                    title: Text(l10n.translate('settings_auto_connect')),
                    subtitle: Text(l10n.translate('settings_auto_connect_desc')),
                    value: settings.autoConnect,
                    onChanged: (value) => settings.setAutoConnect(value),
                  ),
                  SwitchListTile(
                    title: Text(l10n.translate('settings_system_proxy')),
                    subtitle: Text(l10n.translate('settings_system_proxy_desc')),
                    value: settings.systemProxy,
                    onChanged: (value) => settings.setSystemProxy(value),
                  ),
                  ListTile(
                    title: const Text('代理模式'),
                    subtitle: Text(_getProxyModeText(settings.proxyMode)),
                    trailing: const Icon(Icons.chevron_right),
                    onTap: () => _showProxyModeDialog(context, settings),
                  ),
                  ListTile(
                    title: const Text('连接超时'),
                    subtitle: Text('${settings.connectionTimeout} 秒'),
                    trailing: const Icon(Icons.chevron_right),
                    onTap: () => _showTimeoutDialog(context, settings),
                  ),
                ],
              ),
              _SettingsSection(
                title: l10n.translate('settings_subscription'),
                children: [
                  SwitchListTile(
                    title: Text(l10n.translate('settings_auto_update')),
                    subtitle: Text(l10n.translate('settings_auto_update_desc')),
                    value: settings.autoUpdate,
                    onChanged: (value) => settings.setAutoUpdate(value),
                  ),
                  ListTile(
                    title: Text(l10n.translate('settings_update_interval')),
                    subtitle: Text('${settings.updateInterval} ${l10n.translate('settings_connection') == 'Connection' ? 'hours' : '小时'}'),
                    trailing: const Icon(Icons.chevron_right),
                    onTap: () => _showIntervalDialog(context, settings),
                  ),
                ],
              ),
              _SettingsSection(
                title: l10n.translate('settings_core'),
                children: [
                  SwitchListTile(
                    title: Text(l10n.translate('settings_mux')),
                    subtitle: Text(l10n.translate('settings_mux_desc')),
                    value: settings.mux,
                    onChanged: (value) => settings.setMux(value),
                  ),
                  SwitchListTile(
                    title: Text(l10n.translate('settings_allow_insecure')),
                    subtitle: Text(l10n.translate('settings_allow_insecure_desc')),
                    value: settings.allowInsecure,
                    onChanged: (value) => settings.setAllowInsecure(value),
                  ),
                  SwitchListTile(
                    title: const Text('流量嗅探'),
                    subtitle: const Text('自动识别流量类型'),
                    value: settings.enableSniffing,
                    onChanged: (value) => settings.setEnableSniffing(value),
                  ),
                  SwitchListTile(
                    title: const Text('启用 IPv6'),
                    subtitle: const Text('允许 IPv6 连接'),
                    value: settings.enableIPv6,
                    onChanged: (value) => settings.setEnableIPv6(value),
                  ),
                  ListTile(
                    title: const Text('DNS 服务器'),
                    subtitle: Text(settings.dnsServer),
                    trailing: const Icon(Icons.chevron_right),
                    onTap: () => _showDnsDialog(context, settings),
                  ),
                  ListTile(
                    title: const Text('TCP 并发数'),
                    subtitle: Text('${settings.tcpConcurrency} 个连接'),
                    trailing: const Icon(Icons.chevron_right),
                    onTap: () => _showConcurrencyDialog(context, settings),
                  ),
                  ListTile(
                    title: const Text('日志级别'),
                    subtitle: Text(_getLogLevelText(settings.logLevel)),
                    trailing: const Icon(Icons.chevron_right),
                    onTap: () => _showLogLevelDialog(context, settings),
                  ),
                ],
              ),
              _SettingsSection(
                title: l10n.translate('settings_appearance'),
                children: [
                  ListTile(
                    title: Text(l10n.translate('settings_theme')),
                    subtitle: Text(_getThemeText(l10n, settings.theme)),
                    trailing: const Icon(Icons.chevron_right),
                    onTap: () => _showThemeDialog(context, l10n, settings),
                  ),
                  ListTile(
                    title: Text(l10n.translate('settings_language')),
                    subtitle: Text(settings.language == 'zh' ? '中文' : 'English'),
                    trailing: const Icon(Icons.chevron_right),
                    onTap: () => _showLanguageDialog(context, settings),
                  ),
                  SwitchListTile(
                    title: const Text('标题栏显示流量'),
                    subtitle: const Text('在标题栏显示实时流量'),
                    value: settings.showTrafficInTitle,
                    onChanged: (value) => settings.setShowTrafficInTitle(value),
                  ),
                  SwitchListTile(
                    title: const Text('显示节点序号'),
                    subtitle: const Text('在服务器列表中显示序号'),
                    value: settings.showServerIndex,
                    onChanged: (value) => settings.setShowServerIndex(value),
                  ),
                ],
              ),
              _SettingsSection(
                title: '通知',
                children: [
                  SwitchListTile(
                    title: const Text('启用通知'),
                    subtitle: const Text('连接状态改变时显示通知'),
                    value: settings.enableNotifications,
                    onChanged: (value) => settings.setEnableNotifications(value),
                  ),
                  SwitchListTile(
                    title: const Text('声音'),
                    subtitle: const Text('通知时播放声音'),
                    value: settings.soundEnabled && settings.enableNotifications,
                    onChanged: settings.enableNotifications 
                        ? (value) => settings.setSoundEnabled(value)
                        : null,
                  ),
                  SwitchListTile(
                    title: const Text('震动'),
                    subtitle: const Text('通知时震动'),
                    value: settings.vibrationEnabled && settings.enableNotifications,
                    onChanged: settings.enableNotifications
                        ? (value) => settings.setVibrationEnabled(value)
                        : null,
                  ),
                ],
              ),
              _SettingsSection(
                title: l10n.translate('settings_about'),
                children: [
                  ListTile(
                    title: const Text('服务器诊断'),
                    subtitle: const Text('检测和修复服务器ID重复问题'),
                    leading: const Icon(Icons.medical_services),
                    trailing: const Icon(Icons.chevron_right),
                    onTap: () {
                      Navigator.of(context).push(
                        MaterialPageRoute(
                          builder: (context) => const ServerDiagnosticPage(),
                        ),
                      );
                    },
                  ),
                  const Divider(),
                  ListTile(
                    title: Text(l10n.translate('settings_version')),
                    subtitle: const Text('1.0.0'),
                  ),
                  ListTile(
                    title: Text(l10n.translate('settings_check_update')),
                    trailing: const Icon(Icons.chevron_right),
                    onTap: () {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('已是最新版本')),
                      );
                    },
                  ),
                  ListTile(
                    title: const Text('GitHub'),
                    subtitle: const Text('查看源代码'),
                    trailing: const Icon(Icons.chevron_right),
                    onTap: () {
                      // Open GitHub
                    },
                  ),
                  ListTile(
                    title: const Text('开源许可'),
                    trailing: const Icon(Icons.chevron_right),
                    onTap: () {
                      showLicensePage(context: context);
                    },
                  ),
                ],
              ),
            ],
          );
        },
      ),
    );
  }

  String _getThemeText(AppLocalizations l10n, String theme) {
    switch (theme) {
      case 'light':
        return l10n.translate('theme_light');
      case 'dark':
        return l10n.translate('theme_dark');
      default:
        return l10n.translate('theme_system');
    }
  }

  String _getProxyModeText(String mode) {
    switch (mode) {
      case 'global':
        return '全局代理';
      case 'rule':
        return '规则代理';
      case 'direct':
        return '直连';
      default:
        return '全局代理';
    }
  }

  String _getLogLevelText(LogLevel level) {
    switch (level) {
      case LogLevel.error:
        return '错误';
      case LogLevel.warning:
        return '警告';
      case LogLevel.info:
        return '信息';
      case LogLevel.debug:
        return '调试';
    }
  }

  void _showThemeDialog(BuildContext context, AppLocalizations l10n, SettingsProvider settings) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(l10n.translate('settings_theme')),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            RadioListTile<String>(
              title: Text(l10n.translate('theme_light')),
              value: 'light',
              groupValue: settings.theme,
              onChanged: (value) {
                settings.setTheme(value!);
                Navigator.pop(context);
              },
            ),
            RadioListTile<String>(
              title: Text(l10n.translate('theme_dark')),
              value: 'dark',
              groupValue: settings.theme,
              onChanged: (value) {
                settings.setTheme(value!);
                Navigator.pop(context);
              },
            ),
            RadioListTile<String>(
              title: Text(l10n.translate('theme_system')),
              value: 'system',
              groupValue: settings.theme,
              onChanged: (value) {
                settings.setTheme(value!);
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
    );
  }

  void _showLanguageDialog(BuildContext context, SettingsProvider settings) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择语言 / Select Language'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            RadioListTile<String>(
              title: const Text('中文'),
              value: 'zh',
              groupValue: settings.language,
              onChanged: (value) {
                settings.setLanguage(value!);
                Navigator.pop(context);
              },
            ),
            RadioListTile<String>(
              title: const Text('English'),
              value: 'en',
              groupValue: settings.language,
              onChanged: (value) {
                settings.setLanguage(value!);
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
    );
  }

  void _showIntervalDialog(BuildContext context, SettingsProvider settings) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('更新间隔'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            for (var interval in [1, 6, 12, 24, 48, 72])
              RadioListTile<int>(
                title: Text('$interval 小时'),
                value: interval,
                groupValue: settings.updateInterval,
                onChanged: (value) {
                  settings.setUpdateInterval(value!);
                  Navigator.pop(context);
                },
              ),
          ],
        ),
      ),
    );
  }

  void _showProxyModeDialog(BuildContext context, SettingsProvider settings) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('代理模式'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            RadioListTile<String>(
              title: const Text('全局代理'),
              subtitle: const Text('所有流量通过代理'),
              value: 'global',
              groupValue: settings.proxyMode,
              onChanged: (value) {
                settings.setProxyMode(value!);
                Navigator.pop(context);
              },
            ),
            RadioListTile<String>(
              title: const Text('规则代理'),
              subtitle: const Text('根据规则选择代理'),
              value: 'rule',
              groupValue: settings.proxyMode,
              onChanged: (value) {
                settings.setProxyMode(value!);
                Navigator.pop(context);
              },
            ),
            RadioListTile<String>(
              title: const Text('直连'),
              subtitle: const Text('不使用代理'),
              value: 'direct',
              groupValue: settings.proxyMode,
              onChanged: (value) {
                settings.setProxyMode(value!);
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
    );
  }

  void _showTimeoutDialog(BuildContext context, SettingsProvider settings) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('连接超时'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            for (var timeout in [10, 20, 30, 60, 120])
              RadioListTile<int>(
                title: Text('$timeout 秒'),
                value: timeout,
                groupValue: settings.connectionTimeout,
                onChanged: (value) {
                  settings.setConnectionTimeout(value!);
                  Navigator.pop(context);
                },
              ),
          ],
        ),
      ),
    );
  }

  void _showDnsDialog(BuildContext context, SettingsProvider settings) {
    final controller = TextEditingController(text: settings.dnsServer);
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('DNS 服务器'),
        content: TextField(
          controller: controller,
          decoration: const InputDecoration(
            hintText: '例如: 8.8.8.8',
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              settings.setDnsServer(controller.text);
              Navigator.pop(context);
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showConcurrencyDialog(BuildContext context, SettingsProvider settings) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('TCP 并发数'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            for (var count in [4, 8, 16, 32, 64])
              RadioListTile<int>(
                title: Text('$count 个连接'),
                value: count,
                groupValue: settings.tcpConcurrency,
                onChanged: (value) {
                  settings.setTcpConcurrency(value!);
                  Navigator.pop(context);
                },
              ),
          ],
        ),
      ),
    );
  }

  void _showLogLevelDialog(BuildContext context, SettingsProvider settings) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('日志显示级别'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            RadioListTile<LogLevel>(
              title: const Text('错误'),
              subtitle: const Text('只显示错误日志'),
              value: LogLevel.error,
              groupValue: settings.logLevel,
              onChanged: (value) {
                settings.setLogLevel(value!);
                Navigator.pop(context);
              },
            ),
            RadioListTile<LogLevel>(
              title: const Text('警告'),
              subtitle: const Text('显示警告和错误'),
              value: LogLevel.warning,
              groupValue: settings.logLevel,
              onChanged: (value) {
                settings.setLogLevel(value!);
                Navigator.pop(context);
              },
            ),
            RadioListTile<LogLevel>(
              title: const Text('信息'),
              subtitle: const Text('显示常规信息'),
              value: LogLevel.info,
              groupValue: settings.logLevel,
              onChanged: (value) {
                settings.setLogLevel(value!);
                Navigator.pop(context);
              },
            ),
            RadioListTile<LogLevel>(
              title: const Text('调试'),
              subtitle: const Text('显示所有日志（包括调试）'),
              value: LogLevel.debug,
              groupValue: settings.logLevel,
              onChanged: (value) {
                settings.setLogLevel(value!);
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
    );
  }
}

class _SettingsSection extends StatelessWidget {
  final String title;
  final List<Widget> children;

  const _SettingsSection({
    required this.title,
    required this.children,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(16, 24, 16, 8),
          child: Text(
            title,
            style: TextStyle(
              color: Theme.of(context).colorScheme.primary,
              fontSize: 14,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        ...children,
      ],
    );
  }
}
